package org.lzy.shop.database.dao

import androidx.room.Dao
import androidx.room.Delete
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import androidx.room.Update
import org.lzy.shop.database.entity.CartItemEntity

@Dao
interface CartItemDao {
    @Insert(onConflict = OnConflictStrategy.REPLACE)
    suspend fun insert(cartItem: CartItemEntity): Long

    @Update
    suspend fun update(cartItem: CartItemEntity)

    @Delete
    suspend fun delete(cartItem: CartItemEntity)

    @Query("DELETE FROM cart_items WHERE id = :id")
    suspend fun deleteById(id: Int)

    @Query("SELECT * FROM cart_items")
    suspend fun getAllCartItems(): List<CartItemEntity>

    @Query("SELECT * FROM cart_items WHERE is_selected = 1")
    suspend fun getSelectedCartItems(): List<CartItemEntity>

    @Query("UPDATE cart_items SET is_selected = :isSelected")
    suspend fun updateAllSelectedStatus(isSelected: Boolean)

    @Query("UPDATE cart_items SET quantity = :quantity WHERE id = :id")
    suspend fun updateQuantity(id: Int, quantity: Int)

    @Query("UPDATE cart_items SET is_selected = :isSelected WHERE id = :id")
    suspend fun updateSelectedStatus(id: Int, isSelected: Boolean)

    @Query("DELETE FROM cart_items")
    suspend fun clearCart()

    @Query("SELECT IFNULL(COUNT(*), 0) FROM cart_items WHERE is_selected = 1")
    suspend fun getSelectedItemTypesCount(): Int

    @Query("SELECT IFNULL(SUM(quantity), 0) FROM cart_items")
    suspend fun getCartItemCount(): Int

    @Query("SELECT IFNULL(SUM(quantity), 0) FROM cart_items WHERE is_selected = 1")
    suspend fun getSelectedItemCount(): Int

    @Query("SELECT EXISTS(SELECT 1 FROM cart_items)")
    suspend fun isCartEmpty(): Boolean

    @Query("SELECT * FROM cart_items WHERE goods_id = :goodsId")
    suspend fun getCartItemByGoodsId(goodsId: Int): CartItemEntity?
}